// 验证 Token 的中间件

const jwt = require('jsonwebtoken');
const secretKey = 'your_secret_key'; // 替换为你的密钥
function generateToken(userId, realname) {
  const payload = {
    userId,
    realname,
  
  };
  const options = {
    expiresIn: '24h' // Token 有效期为 24 小时
  };
  
  return jwt.sign(payload, secretKey, options);
}

// 验证 JWT
function verifyToken(token) {
  try {
    const decoded = jwt.verify(token, secretKey);
    return { valid: true, decoded };
  } catch (err) {
    return { valid: false, error: err.message };
  }
}

function refreshToken(token) {
  try {
    const decoded = jwt.verify(token, secretKey);
    const newToken = generateToken(decoded.userId, decoded.realname);
    return { valid: true, newToken }; 
  }catch (err) {
    return { valid: false, error: err.message }; 
  }
  
}

outJwt = ["/","/books", "/updateToken", "/login"];

function authenticateToken(req, res, next) {
    // 检查是否为白名单中的路径
    if (outJwt.includes(req.path) || req.path.startsWith('/static')) {
      return next(); // 放行
    }
    const authHeader = req.headers['authorization'];
    let token = '';
    if (authHeader) {
      tokens = authHeader.split(' '); // Bearer Token
      if (tokens.length >= 2) {
        token = tokens[tokens.length -  1]; // 提取 Token 部分
      }
    }
  
    if (!token) {
      return res.status(401).json({ status:401,msg: '缺少 Token' });
    }
    
    jwt.verify(token, secretKey, (err, user) => {
      if (err) {
        return res.status(403).json({ status:401,msg: '无效的 Token' });
      }
      
      req.myuser = user;
      next();
    });
  }
  
  module.exports ={authenticateToken, generateToken, verifyToken, refreshToken};